package com.routz.wxarticlelist.demo.web;

import com.routz.wxarticlelist.demo.WxConstant;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Optional;

//@RestController
//@RequestMapping("/")
/**
 * @Deprecated 微信公众平台配置url时用一次，暂时用不到了
 */
@Deprecated
public class WxBindController {
//    @GetMapping("/")
    public String test(String signature, String timestamp, String nonce, String echostr) {
        //
        ArrayList list = new ArrayList();
        list.add(timestamp);
        list.add(nonce);
        list.add(WxConstant.token);
        list.sort(Comparator.comparing(String::toString));
        StringBuffer sb = new StringBuffer();
        list.forEach(str -> sb.append(str));
        String str = sb.toString();
        String encode = null;
        try {
            encode = SHA1(str);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        System.out.println(signature.equals(encode));
        return echostr;
    }

    public static String SHA1(String str) throws NoSuchAlgorithmException {
        // SHA1签名生成
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(str.getBytes());
        byte[] digest = md.digest();

        StringBuffer hexstr = new StringBuffer();
        String shaHex = "";
        for (int i = 0; i < digest.length; i++) {
            shaHex = Integer.toHexString(digest[i] & 0xFF);
            if (shaHex.length() < 2) {
                hexstr.append(0);
            }
            hexstr.append(shaHex);
        }
        return Optional.ofNullable(hexstr.toString())
                .orElseThrow(()->new IllegalArgumentException("Invalid SHA1."));
    }
}
